import 'package:flutter/cupertino.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:xm_app/common/global/GlobalService.dart';
import 'package:xm_app/common/http/api_response.dart';
import 'package:xm_app/common/logger/LoggerUtil.dart';
import 'package:xm_app/dao/UserDao.dart';
import 'package:xm_app/model/User.dart';
import 'package:xm_app/routes/AppRoutes.dart';

class LoginController extends GetxController {
  final userNameController = new TextEditingController().obs;
  final passwordController = new TextEditingController().obs;
  final hasdeleteIcon = false.obs;
  final globalService = Get.find<GlobalService>();
  @override
  void onInit() {
    super.onInit();
    print("LoginController onInit");
    userNameController.value.addListener(() {
      if (userNameController.value.text == "") {
        hasdeleteIcon.value = false;
      } else {
        hasdeleteIcon.value = true;
      }
    });
  }

  updateUserName(String userName) {
    userNameController.update((val) {
      val.text = userName;
    });
  }

  checkUserAndPwd() {
    if (userNameController.value.text.length == 0) {
      SmartDialog.showToast("用户名为空");
      return false;
    }
    if (passwordController.value.text.length == 0) {
      SmartDialog.showToast("密码为空");
      return false;
    }
    return true;
  }

  register() async {
    if (!checkUserAndPwd()) {
      return;
    }
    ApiResponse res = await UserDao().register(phone: userNameController.value.text, pwd: passwordController.value.text);
    if (res.status == Status.ERROR) {
      SmartDialog.showToast(res.exception.message);
    }
  }

  login() async {
    if (!checkUserAndPwd()) {
      return;
    }
    SmartDialog.showLoading(msg: "登陆中");
    ApiResponse res = await UserDao().login(phone: userNameController.value.text, pwd: passwordController.value.text);
    SmartDialog.dismiss();
    if (res.status == Status.ERROR) {
      SmartDialog.showToast(res.exception.message);
      return;
    }

    //登陆成功  获取登陆信息
    ApiResponse<User> userRes = await UserDao().userInfo();
    logInfo("user $userRes");
    globalService.setUser(userRes.data);
    SmartDialog.showToast("登陆成功！");
    Future.delayed(Duration(milliseconds: 500), () async {
      Get.toNamed(Routes.MAIN);
    });
  }
}
